<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar
      :border="false"
      title="发票服务"
      fixed
      left-icon="back"
      @clickLeft="goBack"
    />

    <view class="content">
      <!-- 主Tab切换 -->
      <view class="main-tabs">
        <view
          v-for="tab in mainTabs"
          :key="tab.value"
          :class="['main-tab-item', { active: currentMainTab === tab.value }]"
          @click="handleMainTabChange(tab.value)"
        >
          <text class="tab-text">{{ tab.label }}</text>
        </view>
      </view>

      <!-- 提示信息 -->
      <view v-if="currentMainTab === 'platform'" class="warning-tip-wrapper">
        <uni-notice-bar
          speed="50"
          single
          scrollable
          show-icon
          background-color="#fffbe6"
          color="#faad14"
          text="暂不支持品牌使用费申请开票"
        />
      </view>

      <!-- 金额统计 -->
      <view class="amount-stats">
        <view class="stat-item">
          <uni-icons type="wallet" size="20" color="#999"></uni-icons>
          <view class="stat-info">
            <text class="stat-label">待开票金额</text>
            <text class="stat-value">¥ {{ pendingAmount }}</text>
          </view>
        </view>
        <view class="stat-item">
          <uni-icons type="checkbox" size="20" color="#999"></uni-icons>
          <view class="stat-info">
            <text class="stat-label">已开票金额</text>
            <text class="stat-value">¥ {{ completedAmount }}</text>
          </view>
        </view>
      </view>

      <!-- 快捷操作 -->
      <view class="quick-actions">
        <view class="action-btn" @click="goToAddress">
          <view class="action-icon">
            <uni-icons type="location" size="28" color="#ff9500"></uni-icons>
          </view>
          <text class="action-text">邮寄地址</text>
        </view>
        <view class="action-btn" @click="goToStampedBill">
          <view class="action-icon">
            <uni-icons type="contact" size="28" color="#ff9500"></uni-icons>
          </view>
          <text class="action-text">盖章账单</text>
        </view>
      </view>

      <view class="p-32rpx bg-white mb-20rpx">
        <!-- 子Tab切换 -->
        <view class="sub-tabs">
          <view
            v-for="tab in subTabs"
            :key="tab.value"
            :class="['sub-tab-item', { active: currentSubTab === tab.value }]"
            @click="handleSubTabChange(tab.value)"
          >
            <text>{{ tab.label }}</text>
          </view>
        </view>

        <!-- 查找按钮 -->
        <view class="search-box" @click="openSearchModal">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
          <text class="search-text">查找</text>
        </view>
      </view>

      <!-- 账单列表 -->
      <view class="bill-list">
        <view v-for="bill in billList" :key="bill.id" class="bill-item">
          <!-- 批量模式下的checkbox在右上角 -->
          <view
            v-if="isBatchMode"
            class="bill-checkbox"
            @click.stop="toggleBillSelection(bill)"
          >
            <view :class="['checkbox-icon', { checked: isSelected(bill.id) }]">
              <uni-icons
                v-if="isSelected(bill.id)"
                type="checkmarkempty"
                size="16"
                color="#fff"
              />
            </view>
          </view>

          <view class="bill-header">
            <text class="bill-id">账单ID：{{ bill.id }}</text>
          </view>

          <view class="bill-amount">
            <text class="amount">¥ {{ bill.amount }}</text>
          </view>

          <view class="bill-info">
            <view class="info-row">
              <text class="info-label">账单周期：</text>
              <text class="info-value">{{ bill.period }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">包含订单数：</text>
              <text class="info-value">{{ bill.orderCount }}</text>
            </view>
          </view>

          <view class="bill-actions">
            <view class="action-link" @click="handleBillDetail(bill)">
              <text>账单明细</text>
            </view>
            <view class="action-link primary" @click="handleCheckInfo(bill)">
              <text>核对开票信息</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="billList.length === 0 && !loading" class="empty-state">
          <text class="empty-text">暂无账单数据</text>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
          <uni-load-more status="loading" />
        </view>
      </view>

      <!-- 底部批量开票按钮 -->
      <view v-if="currentSubTab === 'pending'" class="batch-action">
        <!-- 非批量模式：单个按钮 -->
        <view v-if="!isBatchMode" class="batch-btn" @click="handleBatchInvoice">
          <text>批量开票</text>
        </view>

        <!-- 批量模式：三个按钮 -->
        <view v-else class="batch-action-buttons">
          <view class="action-btn cancel-btn" @click="handleCancelBatch">
            <text>取消</text>
          </view>
          <view class="action-btn detail-btn" @click="handleBatchDetail">
            <text>批量查看明细</text>
          </view>
          <view class="action-btn submit-btn" @click="handleSubmitBatch">
            <text>提交发票</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 查找弹窗 -->
    <uni-popup ref="searchModalRef" type="bottom">
      <view class="search-modal">
        <view class="modal-header">
          <text class="modal-title">查找</text>
          <uni-icons
            type="close"
            size="24"
            color="#666"
            @click="closeSearchModal"
          />
        </view>

        <view class="modal-content">
          <!-- 账单ID -->
          <view class="form-item">
            <text class="form-label">账单ID</text>
            <input
              v-model="searchBillId"
              class="form-input"
              type="text"
              placeholder="请输入内容"
              placeholder-style="color: #ccc"
            />
          </view>

          <!-- 账单周期 -->
          <view class="form-item">
            <text class="form-label">账单周期</text>
            <view class="form-selector" @click="openMonthPicker">
              <text :class="['selector-text', { placeholder: !searchPeriod }]">
                {{ searchPeriod || "请选择" }}
              </text>
              <uni-icons type="forward" size="16" color="#999" />
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <view class="footer-btn reset-btn" @click="resetSearch">
            <text>重置</text>
          </view>
          <view class="footer-btn confirm-btn" @click="confirmSearch">
            <text>搜索</text>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 月份选择器弹窗 -->
    <uni-popup ref="monthPickerRef" type="bottom">
      <view class="month-picker-modal">
        <view class="modal-header">
          <text class="modal-title">查找</text>
          <uni-icons
            type="close"
            size="24"
            color="#666"
            @click="closeMonthPicker"
          />
        </view>

        <view class="picker-content">
          <picker-view
            class="picker-view"
            :value="pickerValue"
            @change="pickerChange"
            :indicator-style="indicatorStyle"
          >
            <picker-view-column>
              <view
                v-for="(month, index) in monthOptions"
                :key="index"
                class="picker-item"
              >
                {{ month.label }}
              </view>
            </picker-view-column>
          </picker-view>
        </view>

        <view class="modal-footer">
          <view class="footer-btn reset-btn" @click="resetMonthPicker">
            <text>重置</text>
          </view>
          <view class="footer-btn confirm-btn" @click="confirmMonthPicker">
            <text>确定</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";

// 主Tab
const mainTabs = ref([
  { label: "商家开票", value: "merchant" },
  { label: "平台开票", value: "platform" },
]);
const currentMainTab = ref("merchant");

// 子Tab
const subTabs = ref([
  { label: "待开票账单", value: "pending" },
  { label: "待提交发票", value: "submit" },
  { label: "开票记录", value: "records" },
]);
const currentSubTab = ref("pending");

// 搜索相关
const searchModalRef = ref(null);
const monthPickerRef = ref(null);
const searchBillId = ref("");
const searchPeriod = ref("");
const selectedMonthIndex = ref(-1);
const selectedMonth = ref(null);

// Picker 相关
const pickerValue = ref([0]);
const indicatorStyle = "height: 50px;";

// 生成月份选项（最近12个月）
const monthOptions = ref([]);

const generateMonthOptions = () => {
  const options = [];
  const now = new Date();

  for (let i = 0; i < 12; i++) {
    const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;

    // 获取该月的最后一天
    const lastDay = new Date(year, month, 0).getDate();

    const startDate = `${year}-${String(month).padStart(2, "0")}-01`;
    const endDate = `${year}-${String(month).padStart(2, "0")}-${lastDay}`;

    options.push({
      label: `${startDate} - ${endDate}`,
      value: { start: startDate, end: endDate },
      year,
      month,
    });
  }

  monthOptions.value = options;
};

// 金额统计
const pendingAmount = computed(() => {
  if (currentMainTab.value === "merchant") {
    return "29463.85";
  } else {
    return "9759.25";
  }
});

const completedAmount = computed(() => {
  return "0.00";
});

// 账单列表
const billList = ref([]);
const loading = ref(false);

// 批量模式
const isBatchMode = ref(false);
const selectedBills = ref([]);

// 模拟数据
const mockMerchantBills = [
  {
    id: "197607410561646977",
    amount: "1,010.88",
    period: "2025/09/01-2025/09/30",
    orderCount: 13,
  },
  {
    id: "196516561261630736",
    amount: "0,060.87",
    period: "2025/08/01-2025/08/31",
    orderCount: 10,
  },
];

const mockPlatformBills = [
  {
    id: "197873629416062792",
    amount: "0.21",
    period: "2025/09/01-2025/09/30",
    orderCount: 1,
  },
  {
    id: "196510167707043423",
    amount: "0",
    period: "2025/08/01-2025/08/31",
    orderCount: 0,
  },
];

// 返回
const goBack = () => {
  uni.navigateBack();
};

// 切换主Tab
const handleMainTabChange = (value) => {
  currentMainTab.value = value;
  loadBillList();
};

// 切换子Tab
const handleSubTabChange = (value) => {
  currentSubTab.value = value;
  loadBillList();
};

// 跳转到邮寄地址
const goToAddress = () => {
  uni.navigateTo({
    url: "/pages/mine/invoice/myAddress",
  });
};

// 跳转到盖章账单
const goToStampedBill = () => {
  uni.showToast({
    title: "盖章账单",
    icon: "none",
  });
  // TODO: 跳转到盖章账单页面
};

// 打开查找弹窗
const openSearchModal = () => {
  searchModalRef.value?.open();
};

// 关闭查找弹窗
const closeSearchModal = () => {
  searchModalRef.value?.close();
};

// 打开月份选择器
const openMonthPicker = () => {
  // 如果已有选中值，设置 picker 位置
  if (selectedMonthIndex.value !== -1) {
    pickerValue.value = [selectedMonthIndex.value];
  } else {
    pickerValue.value = [0]; // 默认选中第一个（最近的月份）
  }
  monthPickerRef.value?.open();
};

// 关闭月份选择器
const closeMonthPicker = () => {
  monthPickerRef.value?.close();
};

// Picker 滚动改变
const pickerChange = (e) => {
  pickerValue.value = e.detail.value;
  selectedMonthIndex.value = e.detail.value[0];
};

// 重置月份选择器
const resetMonthPicker = () => {
  selectedMonthIndex.value = -1;
  pickerValue.value = [0];
  closeMonthPicker();
};

// 确认月份选择器
const confirmMonthPicker = () => {
  const index = pickerValue.value[0];

  if (index === undefined || !monthOptions.value[index]) {
    uni.showToast({
      title: "请选择月份",
      icon: "none",
    });
    return;
  }

  selectedMonthIndex.value = index;
  selectedMonth.value = monthOptions.value[index];
  searchPeriod.value = selectedMonth.value.label;
  closeMonthPicker();
};

// 重置查找
const resetSearch = () => {
  searchBillId.value = "";
  searchPeriod.value = "";
  selectedMonthIndex.value = -1;
  selectedMonth.value = null;
};

// 确认查找
const confirmSearch = () => {
  if (!searchBillId.value && !searchPeriod.value) {
    uni.showToast({
      title: "请输入查找条件",
      icon: "none",
    });
    return;
  }

  closeSearchModal();

  // 根据筛选条件查询账单
  loadBillList();

  const conditions = [];
  if (searchBillId.value) {
    conditions.push(`账单ID: ${searchBillId.value}`);
  }
  if (searchPeriod.value) {
    conditions.push(`周期: ${searchPeriod.value}`);
  }

  uni.showToast({
    title: `查找: ${conditions.join(", ")}`,
    icon: "none",
  });
};

// 账单明细
const handleBillDetail = (bill) => {
  uni.navigateTo({
    url: `/pages/mine/invoice/billInfo?billId=${bill.id}`,
  });
};

// 核对开票信息
const handleCheckInfo = (bill) => {
  uni.navigateTo({
    url: `/pages/mine/invoice/confirmInvoice?billId=${bill.id}`,
  });
};

// 批量开票
const handleBatchInvoice = () => {
  if (billList.value.length === 0) {
    uni.showToast({
      title: "暂无可开票账单",
      icon: "none",
    });
    return;
  }

  // 进入批量模式
  isBatchMode.value = true;
  selectedBills.value = [];
};

// 判断是否选中
const isSelected = (billId) => {
  return selectedBills.value.some((bill) => bill.id === billId);
};

// 切换账单选中状态
const toggleBillSelection = (bill) => {
  const index = selectedBills.value.findIndex((item) => item.id === bill.id);
  if (index > -1) {
    // 取消选中
    selectedBills.value.splice(index, 1);
  } else {
    // 选中
    selectedBills.value.push(bill);
  }
};

// 取消批量模式
const handleCancelBatch = () => {
  isBatchMode.value = false;
  selectedBills.value = [];
};

// 批量查看明细
const handleBatchDetail = () => {
  if (selectedBills.value.length === 0) {
    uni.showToast({
      title: "请选择账单",
      icon: "none",
    });
    return;
  }

  // 将选中的账单ID拼接成字符串
  const billIds = selectedBills.value.map((bill) => bill.id).join(",");

  uni.navigateTo({
    url: `/pages/mine/invoice/billInfo?billIds=${billIds}`,
  });
};

// 提交发票
const handleSubmitBatch = () => {
  if (selectedBills.value.length === 0) {
    uni.showToast({
      title: "请选择账单",
      icon: "none",
    });
    return;
  }

  // TODO: 调用API提交批量开票
  uni.showToast({
    title: `已提交 ${selectedBills.value.length} 个账单`,
    icon: "none",
  });

  // 重置状态
  setTimeout(() => {
    handleCancelBatch();
  }, 1500);
};

// 加载账单列表
const loadBillList = async () => {
  loading.value = true;

  try {
    // TODO: 调用真实API
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 根据当前Tab显示不同数据
    if (currentMainTab.value === "merchant") {
      billList.value =
        currentSubTab.value === "pending" ? mockMerchantBills : [];
    } else {
      billList.value =
        currentSubTab.value === "pending" ? mockPlatformBills : [];
    }
  } catch (error) {
    console.error("加载账单列表失败:", error);
    uni.showToast({
      title: "加载失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  generateMonthOptions();
  loadBillList();
});
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  padding-bottom: 160rpx;
}

// 主Tab
.main-tabs {
  display: flex;
  background-color: #fff;
  padding: 0 32rpx;
}

.main-tab-item {
  flex: 1;
  text-align: center;
  padding: 32rpx 0;
  position: relative;

  &.active {
    .tab-text {
      color: #333;
      font-weight: 600;
    }

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background-color: #ff9500;
      border-radius: 2rpx;
    }
  }
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

// 提示信息
.warning-tip-wrapper {
  border-radius: 8rpx;
  overflow: hidden;
}

// 金额统计
.amount-stats {
  display: flex;
  gap: 20rpx;
  padding: 24rpx;
}

.stat-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16rpx;
  background-color: #fff;
  padding: 24rpx;
  border-radius: 12rpx;
}

.stat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

.stat-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

// 快捷操作
.quick-actions {
  display: flex;
  gap: 20rpx;
  padding: 0 24rpx 24rpx 24rpx;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
  background-color: #fff;
  padding: 24rpx;
  border-radius: 12rpx;

  &:active {
    opacity: 0.8;
  }
}

.action-icon {
  width: 80rpx;
  height: 80rpx;
  background-color: #fff5e6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-text {
  font-size: 26rpx;
  color: #333;
}

// 子Tab
.sub-tabs {
  display: flex;
  background-color: #fff;
}

.sub-tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 26rpx;
  color: #666;
  position: relative;

  &.active {
    color: #333;
    font-weight: 500;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 3rpx;
      background-color: #ff9500;
      border-radius: 2rpx;
    }
  }
}

// 查找框
.search-box {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-top: 16rpx;
  background-color: #f5f5f5;
  padding: 20rpx 24rpx;
  border-radius: 8rpx;

  &:active {
    opacity: 0.8;
  }
}

.search-text {
  flex: 1;
  font-size: 26rpx;
  color: #999;
}

// 账单列表
.bill-list {
  padding: 0 24rpx;
}

.bill-item {
  position: relative;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.bill-checkbox {
  position: absolute;
  top: 24rpx;
  right: 24rpx;
  z-index: 1;
}

.checkbox-icon {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  transition: all 0.3s;

  &.checked {
    background-color: #ff9500;
    border-color: #ff9500;
  }
}

.bill-header {
  margin-bottom: 16rpx;
}

.bill-id {
  font-size: 24rpx;
  color: #666;
}

.bill-amount {
  margin-bottom: 20rpx;
}

.amount {
  font-size: 40rpx;
  color: #ff4d4f;
  font-weight: 700;
}

.bill-info {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-label {
  font-size: 24rpx;
  color: #999;
}

.info-value {
  font-size: 24rpx;
  color: #333;
}

.bill-actions {
  display: flex;
  gap: 20rpx;
}

.action-link {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #666;

  &.primary {
    color: #ff9500;
    border-color: #ff9500;
  }

  &:active {
    opacity: 0.8;
  }
}

// 空状态
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

// 加载状态
.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

// 批量开票按钮
.batch-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.batch-btn {
  height: 88rpx;
  background: linear-gradient(135deg, #ffd000 0%, #ff9500 100%);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #fff;
  font-weight: 600;

  &:active {
    opacity: 0.9;
  }
}

// 批量操作按钮组
.batch-action-buttons {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  border-radius: 12rpx;

  &:active {
    opacity: 0.8;
  }
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.detail-btn {
  background-color: #fff;
  color: #ff9500;
  border: 1rpx solid #ff9500;
}

.submit-btn {
  background: linear-gradient(135deg, #ffd000 0%, #ff9500 100%);
  color: #fff;
  font-weight: 600;
}

// 查找弹窗
.search-modal {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.modal-content {
  padding: 0 32rpx;
}

// 表单项
.form-item {
  display: flex;
  align-items: center;
  padding: 32rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  font-size: 28rpx;
  color: #333;
  width: 150rpx;
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  text-align: right;

  &::placeholder {
    color: #ccc;
  }
}

.form-selector {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8rpx;

  &:active {
    opacity: 0.7;
  }
}

.selector-text {
  font-size: 28rpx;
  color: #333;

  &.placeholder {
    color: #ccc;
  }
}

.modal-footer {
  display: flex;
  gap: 24rpx;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
}

.footer-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;

  &:active {
    opacity: 0.8;
  }
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: linear-gradient(135deg, #ffd000 0%, #ff9500 100%);
  color: #fff;
  font-weight: 600;
}

// 月份选择器弹窗
.month-picker-modal {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  display: flex;
  flex-direction: column;
}

.picker-content {
  padding: 0 32rpx 16rpx;
}

.picker-view {
  height: 400rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  /* 与 indicatorStyle 完全一致，避免选中行偏移 */
  height: 50px;
  line-height: 50px;
  font-size: 28rpx;
  color: #333;
}
</style>
